#include <iostream>
#include <cstring>
#include <string>
#include <unistd.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

#define N 2
#define MAX_SIZE 1024

void Readpipe(int rfd)
{
    char buf[MAX_SIZE];

    int cnt = 5;
    while(true)
    {
        buf[0] = 0;
        ssize_t n = read(rfd, buf, sizeof(buf));
        if(n > 0)
        {
            buf[n] = 0;
            cout << "father" << '[' << getpid() << ']' <<" get a message:" << buf << endl;
        }
        cout << "n:" << n << endl;
    }
}

void Writepipe(int wfd)
{
    char buf[MAX_SIZE];
    string s("I am child");
    pid_t id = getpid();

    int cnt = 5;
    while(true)
    {
        // 清除缓冲区
        buf[0] = 0;

        snprintf(buf, sizeof(buf), "%s:%d",s.c_str(), id);
        ssize_t ret = write(wfd, buf, strlen(buf));
        
        sleep(1);
    }

}


int main()
{
    // 创建并初始化管道文件fd数组
    // pipe[0]读 pipe[1]写
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if(n == -1) return 1;
    
    // 创建子进程
    pid_t id = fork();
    if(id < 0) return 2;
    if(id == 0)
    {
        // child 写
        close(pipefd[0]);

        Writepipe(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    // parent 读
    close(pipefd[1]);

    Readpipe(pipefd[0]);
    pid_t ret = waitpid(id,NULL,0);
    if(ret < 0) return 3;
    cout << "程序已经正常退出" << endl;

    close(pipefd[0]);
    return 0;
}